package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatProperties weChatProperties;

    /**
     * 微信登录业务
     *     1:解析出授权码
     *        找腾讯 发送校验请求
     *           https://api.weixin.qq.com/sns/jscode2session
     *           带四个参数 appid  secret  js_code  grant_type
     *           怎么发 httpclient 发 请求
     *           获取响应结果
     {
     "session_key": "2AoT3WTgzCEy5fBFPxZevg==",
     "openid": "osvjO5WZg1xMemPURANL5rYoewtU",
     "unionid": "o5PB1sw7rvEW6mCUBrsj-d2mUwx0"
     }
     *           {
     "errcode": 40029,
     "errmsg": "invalid code, rid: 686cd2ed-7bac95f3-7b89cf61"
     }
     解析结果中是否带了 openid 就行 如果有说明成功 没有失败
     2:根据openid查询数据库中是否已经存在此用户
     null   不存在  保存用户信息  返回用户信息
     非null  存在  返回用户信息
     3:返回用户对象
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //1:解析code 授权码
        String code = userLoginDTO.getCode();
        // 2: 发请求
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> map = new HashMap<>();//存4个参数
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String json = HttpClientUtil.doGet(url, map);//发请求
        //3: 解析结果 json格式的结果 怎么解析
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        if (openid == null) { //登录失败
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //根据openid 去数据库查询
        User user = userMapper.getByOpenid(openid);
        if (user == null) { //新用户  插入数据库  返回一个User对象 id自增 存openid
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
        }

        return user;
    }
}